import json
import serial

def load_config(config_file):
    """加载配置文件"""
    with open(config_file, 'r', encoding="utf-8") as f:
        configs = json.load(f)
    
    if not isinstance(configs, list):
        raise ValueError("配置文件应该是一个串口配置的列表")
    
    # 为每个配置设置默认值
    for config in configs:
        config.setdefault('bytesize', 8)
        config.setdefault('parity', 'N')
        config.setdefault('stopbits', 1)
        config.setdefault('client_timeout', 30)
        config.setdefault('max_clients', 5)
        config.setdefault('queue_size', 10)
        config.setdefault('serial_timeout', 3.0)
        config.setdefault('debug', False)
        
        # 转换串口参数
        parity_map = {'N': serial.PARITY_NONE, 'E': serial.PARITY_EVEN, 'O': serial.PARITY_ODD}
        config['parity'] = parity_map.get(config['parity'], serial.PARITY_NONE)
        
        stopbits_map = {1: serial.STOPBITS_ONE, 2: serial.STOPBITS_TWO}
        config['stopbits'] = stopbits_map.get(config['stopbits'], serial.STOPBITS_ONE)
    
    return configs